package io.nio;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Buffer 之 allocate
 * Buffer 之 position limit capacity
 * Buffer 之 get put hasRemaining
 * Buffer 之 clear flip compact
 * Buffer 之 从channel读到buffer、从buffer写到channel
 */
public class NioBuffersDemo {

    public static void main(String[] args) {
        BufferDemo();
    }


    private static void BufferDemo(){
        try {
            String mode = "rw";
            String name = "/Users/lining/Desktop/nio/fileChannelTest.txt";
            RandomAccessFile accessFile = new RandomAccessFile(name, mode);
            FileChannel fileChannel = accessFile.getChannel();

            ByteBuffer buffer = ByteBuffer.allocate(48);
            printBuffer(buffer, "New Buffer");
            int readBytes = -1;
            do {
                readBytes = fileChannel.read(buffer);
                printBuffer(buffer, "Read To Buffer");
                System.out.println("Read " + readBytes);

                buffer.flip();
                printBuffer(buffer, "Flip Buffer");
                while (buffer.hasRemaining()) {
                    System.out.print((char) buffer.get());
                }
                System.out.println();
                printBuffer(buffer, "Get From Buffer");
                buffer.clear();
                printBuffer(buffer, "Clear Buffer");
            } while (readBytes != -1);



            accessFile.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void printBuffer(Buffer buffer, String when){
        if(buffer == null) System.out.println("Buffer 为NULL");
        System.out.println(String.format("%s:\t\t\tposition=%s,limit=%s,capacity=%s"
                ,when
                ,buffer.position()
                ,buffer.limit()
                ,buffer.capacity()));
    }
}
